﻿using log4net;
using log4net.Appender;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectClone.Tool
{
    public static class log4netHelper
    {
        static log4netHelper()
        {
            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\log4net.config");
            XmlConfigurator.ConfigureAndWatch(logCfg);
        }

        private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");

        public static void Debug(object message) {
            if (loginfo.IsDebugEnabled) {
                loginfo.Debug(message);
            }
        }

        public static void Info(object message)
        {
            if (loginfo.IsInfoEnabled)
            {
                loginfo.Info(message);
            }
        }
        public static void Error(object message)
        {
            if (loginfo.IsErrorEnabled)
            {
                loginfo.Error(message);
            }
        }
        public static void Fatal(object message)
        {
            if (loginfo.IsFatalEnabled)
            {
                loginfo.Fatal(message);
            }
        }
        public static void Warn(object message)
        {
            if (loginfo.IsWarnEnabled)
            {
                loginfo.Warn(message);
            }
        }

        /// <summary>
        /// 改变默认的日志位置
        /// </summary>
        /// <param name="folder"></param>
        public static void UpdateFolder(string folder)
        {
            var storedPath = LogManager.GetRepository();
            var appenders = storedPath.GetAppenders();
            //var targetFolder = appenders.First(m => m.Name.Equals("InfoAppender")) as RollingFileAppender;//如果是要指定改某个appender,则在这里指定appender
            //targetFolder.File = folder;

            //一般多种日志目录是写在一起
            if (appenders == null) return;
            foreach (var app in appenders)
            {
                var ra = app as RollingFileAppender;
                ra.File = folder + "ErrLogs\\";
                ra.ActivateOptions();
                //if (app.Name.Equals("ErrorAppender") || app.Name.Equals("InfoAppender"))
                //{
                //    var ra = app as RollingFileAppender;
                //    ra.File = folder;
                //    ra.ActivateOptions();
                //}
            }
        }
    }
}
